// 数据库名称和版本
const dbName = 'custom';
const dbVersion = 1;

// 全局变量保存数据库实例
let db;

// 打开数据库
function openDatabase() {
 return new Promise((resolve, reject) => {
  const request = indexedDB.open(dbName, dbVersion);

  // 错误处理
  request.onerror = (event) => {
   console.error('数据库打开失败', event);
   reject('数据库打开失败');
  };

  // 成功处理
  request.onsuccess = (event) => {
   db = request.result;
   console.log('数据库打开成功');
   resolve();
  };

  // 初始化或升级数据库
  request.onupgradeneeded = (event) => {
   db = event.target.result;
   console.log('数据库初始化或升级');

   // 创建对象存储空间（表）
   if (!db.objectStoreNames.contains('users')) {
    const objectStore = db.createObjectStore('users', { keyPath: 'id', autoIncrement: true });

    // 创建索引
    objectStore.createIndex('name', 'name', { unique: false });
    objectStore.createIndex('email', 'email', { unique: true });
   }
  };
 });
}

// 添加数据
function addData(data) {
 return new Promise((resolve, reject) => {
  const transaction = db.transaction(['users'], 'readwrite');
  const objectStore = transaction.objectStore('users');
  const request = objectStore.add(data);

  request.onsuccess = () => {
   console.log('数据添加成功:', data);
   resolve();
  };

  request.onerror = (event) => {
   console.error('数据添加失败', event);
   reject('数据添加失败');
  };
 });
}

// 读取数据
function readData(id) {
 return new Promise((resolve, reject) => {
  const transaction = db.transaction(['users']);
  const objectStore = transaction.objectStore('users');
  const request = objectStore.get(id);

  request.onsuccess = () => {
   if (request.result) {
    console.log('读取数据成功:', request.result);
    resolve(request.result);
   } else {
    console.log('未找到对应id的数据');
    resolve(null);
   }
  };

  request.onerror = (event) => {
   console.error('读取数据失败', event);
   reject('读取数据失败');
  };
 });
}

// 更新数据
function updateData(id, newData) {
 return new Promise((resolve, reject) => {
  const transaction = db.transaction(['users'], 'readwrite');
  const objectStore = transaction.objectStore('users');
  const request = objectStore.put({ ...newData, id });

  request.onsuccess = () => {
   console.log('数据更新成功:', newData);
   resolve();
  };

  request.onerror = (event) => {
   console.error('数据更新失败', event);
   reject('数据更新失败');
  };
 });
}

// 删除数据
function deleteData(id) {
 return new Promise((resolve, reject) => {
  const transaction = db.transaction(['users'], 'readwrite');
  const objectStore = transaction.objectStore('users');
  const request = objectStore.delete(id);

  request.onsuccess = () => {
   console.log(`数据删除成功，id=${id}`);
   resolve();
  };

  request.onerror = (event) => {
   console.error('数据删除失败', event);
   reject('数据删除失败');
  };
 });
}

// 示例：测试增删改查功能
(async function main() {
 try {
  // 打开数据库
  await openDatabase();

  // 添加数据
  await addData({ name: '张三', email: 'zhangsan@example.com' });
  await addData({ name: '李四', email: 'lisi@example.com' });

  // 读取数据
  const data = await readData(1); // 假设我们想读取id为1的数据
  console.log('读取到的数据:', data);

  // 更新数据
  await updateData(1, { name: '张三更新', email: 'zhangsan_new@example.com' });

  // 删除数据
  await deleteData(2); // 删除id为2的数据
 } catch (error) {
  console.error('操作失败:', error);
 }
})();
